package cn.changeforyou.demo.netty.common;

import cn.changeforyou.demo.netty.common.Data.MsgType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author zhyu
 * @date 2021/3/15 16:35
 */
public class YbkjTcpDataEncoder extends MessageToByteEncoder<Data> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Data msg, ByteBuf out) throws Exception {
        out.writeBytes(Data.HEAD.getBytes());
        out.writeBytes(Data.PROJECT_NAME.getBytes());
        MsgType msgType = msg.getMsgType();
        out.writeByte(msgType.getCode());
        Object content = msg.getContent();
        byte[] contentBytes;
        if (msgType == MsgType.json || msgType == MsgType.response || msgType == MsgType.req) {
            contentBytes = JsonUtils.toJson(content).getBytes();
        } else if (msgType == MsgType.heart) {
            contentBytes = Data.HEART_BEAT_CONTENT.getBytes();
        } else {
            contentBytes = ((String) content).getBytes();
        }

        out.writeShort(contentBytes.length);
        out.writeBytes(contentBytes);
        out.writeLong(msg.getTimestamp());
        out.writeBytes(Data.FOOT.getBytes());
    }
}
